package main

import (
	"fmt"
	"os"

	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"techoiceness.com/aiagent/llm-gateway/internal/config"
	"techoiceness.com/aiagent/llm-gateway/internal/database"
	"techoiceness.com/aiagent/llm-gateway/internal/logger"
)

var migrateCmd = &cobra.Command{
	Use:   "migrate",
	Short: "运行数据库迁移",
	Long:  `运行数据库迁移，创建或更新数据库表结构`,
	Run: func(cmd *cobra.Command, args []string) {
		cfg, err := config.LoadConfig()
		if err != nil {
			fmt.Fprintf(os.Stderr, "错误: 加载配置失败: %v\n", err)
			os.Exit(1)
		}

		logger.Initialize()

		// 迁移系统数据库
		systemDB, err := database.NewDatabase(&cfg.Database)
		if err != nil {
			log.Fatal().Err(err).Msg("连接系统数据库失败")
		}

		if err := database.MigrateSystem(systemDB); err != nil {
			log.Fatal().Err(err).Msg("系统数据库迁移失败")
		}

		log.Info().Msg("数据库迁移成功完成")
		fmt.Println("数据库迁移完成。")
	},
}
